using System;
using System.Reflection;
using System.Threading.Tasks;
using UnityEngine;
using Framework.Data.Config;
using Framework.Manager;

namespace Framework.UI
{
    public class UILanguage : MonoBehaviour
    {
        [SerializeField]
        private string mConfigName = string.Empty;
        [SerializeField]
        private string mConfigId = string.Empty;

        private UIText mUIText = null;
        private string mLanguage = string.Empty;

        private async void Start()
        {
#if !RESOURCE
            mUIText = this.gameObject.GetComponent<UIText>();

            if (!string.IsNullOrEmpty(mConfigName) && !string.IsNullOrEmpty(mConfigId))
                await SetUITextAsync(mConfigName, mConfigId);
#endif
        }

        private string ProcessConfigName(string pConfigName)
        {
            string configName = string.Empty;

            string language = ManagerCollection.DataManager.GameConfiguration.Language;
            if (string.IsNullOrEmpty(language))
                configName = pConfigName;
            else
                configName = $"{pConfigName}_{language}";

            return configName;
        }

        /// <summary>设置UIText（异步，会加载Config）</summary>
        public async Task SetUITextAsync(string pConfigName, string pConfigId)
        {
            string configName = ProcessConfigName(pConfigName);
            bool result = await ManagerCollection.LoadManager.LoadAssetAsync(configName);
            if (result)
            {
                SetLanguage(pConfigName, pConfigId);
                mUIText.Text = mLanguage;
            }
            else
            {
                Debug.LogWarning($"Load config failed. ConfigName is {configName}, ConfigId is {pConfigId}");
            }
        }

        /// <summary>设置UIText</summary>
        public void SetUIText(string pConfigName, string pConfigId)
        {
            SetLanguage(pConfigName, pConfigId);
            mUIText.Text = mLanguage;
        }

        public void SetLanguage(string pConfigName, string pConfigId)
        {
            mConfigName = pConfigName;
            mConfigId = pConfigId;

            string configName = ProcessConfigName(pConfigName);
            IConfigBase config = ManagerCollection.DataManager.GetConfig(configName, mConfigId);
            if (config != null)
            {
                Type configType = config.GetType();
                FieldInfo fieldInfo = configType.GetField("language");
                mLanguage = fieldInfo.GetValue(config) as string;
            }
            else
            {
                Debug.LogWarning($"Get config is null. ConfigName is {configName}, ConfigId is {pConfigId}");
            }
        }

        public string GetLanguage()
        {
            return mLanguage;
        }
    }
}